package org.balabala.gateway.controller;


import com.google.code.kaptcha.Producer;
import feign.FeignException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.balabala.gateway.entity.SysMenuEntity;
import org.balabala.gateway.entity.SysRoleEntity;
import org.balabala.gateway.entity.SysUserEntity;
import org.balabala.gateway.feign.AdminFeign;
import org.balabala.gateway.response.Resp;
import org.balabala.gateway.response.ResponseInfo;
import org.balabala.gateway.utils.PasswordForm;
import org.balabala.gateway.utils.SysLoginForm;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
@CrossOrigin
@RequestMapping("/admin")
public class AdminRouter extends AbstractController {
    @Resource
    private AdminFeign adminFeign;

    @Resource
    private Producer producer;

    /**
     * 获取验证码
     *
     * @param response
     * @param uuid
     * @throws IOException
     */
    @GetMapping("/get_verification_code")
    public void getVerificationCode(HttpServletResponse response, String uuid) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        if (StringUtils.isBlank(uuid)) {
            log.error("uuid cannot be null");
        }


        log.info("getVerificationCode parameter uuid : " + uuid);
        String code = producer.createText();
        BufferedImage image = producer.createImage(code);

        try {
            Resp resp = adminFeign.getCaptcha(uuid, code);
            if (resp.getCode() == 0) {
                log.info("adminFeign.getCaptcha request succeed");
            } else {
                log.info("adminFeign.getCaptcha request error message: " + resp.get("msg"));
            }
        } catch (FeignException e) {
            log.error("adminFeign.getCaptcha request error : " + e);
        }

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }


    /**
     * 管理后台登录
     *
     * @param form
     * @return
     */
    @PostMapping("/sys/login")
    public Map<String, Object> login(@RequestBody SysLoginForm form) {
        log.info("login parameter form : " + form);
        try {
            return adminFeign.login(form);
        } catch (FeignException e) {
            log.error("adminFeign.login request error : " + e);
        }
        return null;
    }


    /**
     * 管理后台退出
     *
     * @return
     */
    @PostMapping("/sys/logout")
    public Resp logout() {
        try {
            return adminFeign.logout(getUserId());
        } catch (FeignException e) {
            log.error("adminFeign.logout request error : " + e);
        }
        return Resp.error(ResponseInfo.RPC_ERROR);
    }


    /**
     * 获取用户信息
     *
     * @return
     */
    @GetMapping("/sys/user/info")
    public Resp info() {
        return Resp.ok().put("user", getUser());
    }


    /**
     * 根据id查询用户
     *
     * @param userid
     * @return
     */
    @GetMapping("/sys/user/info/{id}")
    public Resp infoByUserId(@PathVariable("id") Long userid) {
        log.info("infoByUserId parameter userid : " + userid);
        try {
            return adminFeign.infobyUid(userid);
        } catch (FeignException e) {
            log.error("adminFeign.infobyUid request error : " + e);
        }
        return Resp.error(ResponseInfo.RPC_ERROR);
    }


    /**
     * 修改密码
     *
     * @param form
     * @return
     */
    @PostMapping("/sys/user/password")
    public Resp password(@RequestBody PasswordForm form) {
        form.setUserId(getUserId());
        log.info("password parameter form : " + form);
        try {
            return adminFeign.password(form);
        } catch (FeignException e) {
            log.error("adminFeign.password request error : " + e);
        }
        return Resp.error(ResponseInfo.RPC_ERROR);
    }


    /**
     * 获取用户列表
     *
     * @param params
     * @return
     */
    @GetMapping("/sys/user/list")
    public Resp list(@RequestParam Map<String, Object> params) {
        log.info("password parameter params : " + params);
        try {
            return adminFeign.list(params);
        } catch (FeignException e) {
            log.error("adminFeign.list request error : " + e);
        }
        return Resp.error(ResponseInfo.RPC_ERROR);
    }


    /**
     * 封禁用户
     *
     * @param userIds
     * @return
     */
    @PostMapping("/sys/user/delete")
    public Resp deleteUser(@RequestBody Long[] userIds) {
        if (userIds != null && userIds.length > 0) {
            log.error("deleteUser parameter userIds is null");
            return Resp.error(ResponseInfo.PARAMETER_ERROR);
        }

        log.info("deleteUser parameter userIds : " + userIds);

        try {
            return adminFeign.deleteUser(userIds);
        } catch (FeignException e) {
            log.error("adminFeign.deleteUser request error : " + e);
        }

        return Resp.error(ResponseInfo.RPC_ERROR);

    }


    /**
     * 更新管理员信息
     *
     * @param user
     * @return
     */
    @PostMapping("/sys/user/update")
    public Resp update(@RequestBody SysUserEntity user) {
        if (user == null) {
            log.error("update parameter is null");
            return Resp.error(ResponseInfo.PARAMETER_ERROR);
        }

        log.error("update parameter user : " + user);

        try {
            return adminFeign.update(user);
        }catch (FeignException e){
            log.error("adminFeign.update request error : " + e);
        }

        return Resp.error(ResponseInfo.RPC_ERROR);
    }


    /**
     * 添加管理员
     * @param user
     * @return
     */
    @PostMapping("/sys/user/save")
    public Resp saveUser(@RequestBody SysUserEntity user) {
        if (user == null) {
            log.error("update parameter is null");
            return Resp.error(ResponseInfo.PARAMETER_ERROR);
        }

        log.error("update parameter user : " + user);

        try {
            return adminFeign.saveUser(user);
        }catch (FeignException e){
            log.error("adminFeign.saveUser request error : " + e);
        }

        return Resp.error(ResponseInfo.RPC_ERROR);
    }


    /**
     * 获取角色列表
     * @param params
     * @return
     */
    @GetMapping("/sys/role/list")
    public Resp roleList(@RequestParam Map<String, Object> params) {
        log.info("roleList parameter params : " + params);

        try{
            return adminFeign.roleList(params);
        }catch (Exception e){
            log.error("adminFeign.roleListr request error : " + e);
        }

        return Resp.error(ResponseInfo.RPC_ERROR);
    }


    /**
     * 查询用户角色
     * @return
     */
    @GetMapping("/sys/role/select")
    public Resp select() {
        try {
            return adminFeign.select(getUserId());
        }catch (FeignException e){
            log.error("adminFeign.select request error : " + e);
        }

        return Resp.error(ResponseInfo.RPC_ERROR);
    }


    /**
     * 根据角色id查询角色信息
     * @param roleId
     * @return
     */
    @GetMapping("/sys/role/info/{roleId}")
    public Resp info(@PathVariable Long roleId) {
        if (roleId == null){
            log.error("info parameter roleId is null");
            return Resp.error(ResponseInfo.PARAMETER_ERROR);
        }

        log.error("info parameter roleId : " + roleId);

        try {
            return adminFeign.infobyUid(roleId);
        }catch (FeignException e){
            log.error("adminFeign.infobyUid request error : " + e);
        }

        return Resp.error(ResponseInfo.RPC_ERROR);
    }


    /**
     * 添加角色
     * @param role
     * @return
     */
    @PostMapping("/sys/role/save")
    public Resp roleSave(@RequestBody SysRoleEntity role) {
        if (role == null){
            log.error("roleSave parameter role is null");
            return Resp.error(ResponseInfo.PARAMETER_ERROR);
        }

        log.error("roleSave parameter role : " + role);

        try {
            return adminFeign.save(role);
        }catch (FeignException e){
            log.error("adminFeign.save request error : " + e);
        }

        return Resp.error(ResponseInfo.RPC_ERROR);
    }


    /**
     * 更新角色信息
     * @param role
     * @return
     */
    @PostMapping("/sys/role/update")
    public Resp update(@RequestBody SysRoleEntity role) {
        if (role == null){
            log.error("update parameter role is null");
            return Resp.error(ResponseInfo.PARAMETER_ERROR);
        }

        log.error("update parameter role : " + role);

        try {
            return adminFeign.roleUpdate(role);
        }catch (FeignException e){
            log.error("adminFeign.roleUpdate request error : " + e);
        }

        return Resp.error(ResponseInfo.RPC_ERROR);
    }


    /**
     * 删除角色
     * @param roleIds
     * @return
     */
    @PostMapping("/sys/role/delete")
    public Resp deleteRole(@RequestBody Long[] roleIds) {
        if (roleIds == null || roleIds.length <= 0){
            log.error("deleteRole parameter roleIds is null");
            return Resp.error(ResponseInfo.PARAMETER_ERROR);
        }

        log.error("deleteRole parameter roleIds : " + roleIds);

        try {
            return adminFeign.deleteRole(roleIds);
        }catch (FeignException e){
            log.error("adminFeign.deleteRole request error : " + e);
        }

        return Resp.error(ResponseInfo.RPC_ERROR);
    }


    /**
     * 获取导航栏列表
     * @return
     */
    @GetMapping("/sys/menu/nav")
    public Resp nav() {
        try {
            Long userId = getUserId();
            return adminFeign.nav(userId);
        }catch (FeignException e){
            log.error("adminFeign.nav request error : " + e);
        }

        return Resp.error(ResponseInfo.RPC_ERROR);
    }


    /**
     * 获取菜单列表
     * @return
     */
    @GetMapping("/sys/menu/list")
    public List<SysMenuEntity> navList() {
        try{
            return adminFeign.navList();
        }catch (FeignException e){
            log.error("adminFeign.navList request error : " + e);
        }

        return null;
    }

    /**
     * 查询菜单列表
     * @return
     */
    @GetMapping("/sys/menu/select")
    public Resp menuSelect() {
        try {
            return adminFeign.menuSelect();
        }catch (FeignException e){
            log.error("adminFeign.menuSelect request error : " + e);
        }

        return Resp.error(ResponseInfo.RPC_ERROR);
    }

    /**
     * 获取菜单选项
     * @param menuId
     * @return
     */
    @GetMapping("/sys/menu/info/menuid")
    public Resp menuInfo(@RequestParam Long menuId) {
        try {
            return adminFeign.menuInfo(menuId);
        }catch (FeignException e){
            log.error("adminFeign.menuInfo request error : " + e);
        }

        return Resp.error(ResponseInfo.RPC_ERROR);
    }


    /**
     * 添加菜单
     * @param menu
     * @return
     */
    @PostMapping("/sys/menu/save")
    public Resp saveMenu(@RequestBody SysMenuEntity menu) {
        if (menu == null){
            log.error("saveMenu parameter menu is null");
            return Resp.error(ResponseInfo.PARAMETER_ERROR);
        }

        log.error("saveMenu parameter menu : " + menu);

        try {
            return adminFeign.saveMenu(menu);
        }catch (FeignException e){
            log.error("adminFeign.saveMenu request error : " + e);
        }

        return Resp.error(ResponseInfo.RPC_ERROR);
    }


    /**
     * 更新菜单信息
     * @param menu
     * @return
     */
    @PostMapping("/sys/menu/update")
    public Resp updateMenu(@RequestBody SysMenuEntity menu) {
        return adminFeign.updateMenu(menu);
    }


    /***
     * 删除菜单
     * @param menuId
     * @return
     */
    @PostMapping("/sys/menu/delete/{id}")
    public Resp delete(@PathVariable("id") long menuId) {
        return adminFeign.deleteMenu(menuId);
    }

}
